package models

import net.scalax.cpoi.api._
import net.scalax.cpoi.rw.CellWritersImplicits
import org.apache.poi.common.usermodel.HyperlinkType
import org.apache.poi.ss.usermodel.Cell

import scala.util.Try

case class UrlWrap(showText: String, url: String)

trait CusPoiOperations extends CellWritersImplicits {

  implicit val urlWriter: CellWriter[UrlWrap] = {
    new CellWriter[UrlWrap] {
      override def setValue(cell: Cell, value: UrlWrap): Try[CPoiDone] =
        stringWriter.setValue(cell, value.showText).flatMap { (s: CPoiDone) =>
          Try {
            val workbook = cell.getRow.getSheet.getWorkbook
            val createHelper = workbook.getCreationHelper
            val link = createHelper.createHyperlink(HyperlinkType.URL)
            link.setAddress(value.url)
            cell.setHyperlink(link)
            s
          }
        }
    }
  }
}
